<template>
  <div class="guide-category-table">
    <!-- 顶栏区域 -->
    <div class="top-bar">
      <div class="top-bar-content">
        <div class="page-title">
          <!-- <h2>指南类别管理</h2>
          <p>管理康复指南的分类信息</p> -->
        </div>
        <div class="top-bar-actions">
          <t-tag theme="primary" variant="light"> 共 {{ pagination.total }} 条记录 </t-tag>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-btn-group">
        <t-space>
          <t-button theme="primary" @click="handleAddCategory" shape="round">
            <template #icon>
              <t-icon name="plus" />
            </template>
            新增类别
          </t-button>
          <t-button theme="danger" shape="round" :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">
            <template #icon>
              <t-icon name="delete" />
            </template>
            批量删除 ({{ selectedRowKeys.length }})
          </t-button>
        </t-space>
      </div>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-container">
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :loading="dataLoading"
        :selected-row-keys="selectedRowKeys"
        :bordered="false"
        :stripe="true"
        row-hover-divider
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="onSelectChange"
      >
        <!-- 序号列 -->
        <template #index="{ rowIndex }">
          <div class="index-cell">
            {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
          </div>
        </template>

        <!-- 类别名称列 -->
        <template #name="{ row }">
          <div class="name-cell">
            <t-tooltip :content="row.name" placement="top">
              <div class="name-content">
                <t-icon name="folder" class="name-icon" />
                <span class="name-text ellipsis">{{ row.name }}</span>
              </div>
            </t-tooltip>
          </div>
        </template>

        <!-- 创建时间列 -->
        <template #createTime="{ row }">
          <div class="time-cell">
            <t-icon name="time" class="time-icon" />
            <span class="time-text">{{ formatDateTime(row.createTime) }}</span>
          </div>
        </template>

        <!-- 操作列 -->
        <template #op="slotProps">
          <div class="operation-cell">
            <t-space>
              <t-button size="small" theme="primary" variant="text" @click="handleEdit(slotProps.row)">
                <template #icon>
                  <t-icon name="edit" />
                </template>
                编辑
              </t-button>
              <t-button size="small" theme="danger" variant="text" @click="handleClickDelete(slotProps)">
                <template #icon>
                  <t-icon name="delete" />
                </template>
                删除
              </t-button>
            </t-space>
          </div>
        </template>
      </t-table>
    </div>

    <!-- 新增/编辑类别弹窗 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="dialogTitle"
      width="500px"
      placement="center"
      :footer="false"
      :close-on-overlay-click="false"
    >
      <t-form ref="formRef" :data="formData" :rules="rules" :label-width="80" colon @submit="onSubmit">
        <t-form-item label="类别名称" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入类别名称"
            :maxlength="25"
            show-limit-number
            clearable
            :status="formData.name.trim() === '' ? 'error' : undefined"
          />
        </t-form-item>

        <t-form-item>
          <t-space>
            <t-button theme="primary" type="submit" :loading="submitLoading"> 确定 </t-button>
            <t-button theme="default" variant="base" @click="dialogVisible = false"> 取消 </t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { addGuideCategory, deleteGuideCategory, getGuideCategoryList, updateGuideCategory } from '@/api/guideCategory';
import type { GuideCategoryRequest, GuideCategoryResponse } from '@/api/model/guideCategoryModel';
import { prefix } from '@/config/global';
import { DEFAULT_PAGINATION } from '@/constants'; // 导入全局分页配置
import { useSettingStore } from '@/store';
import { formatDateTime } from '@/utils/date';
import type { FormRule, PageInfo, PrimaryTableCol } from 'tdesign-vue-next';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { computed, onActivated, ref } from 'vue';

// 中文注释：定义组件名称
defineOptions({
  name: 'GuideCategory',
});

// 表格列配置
const COLUMNS: PrimaryTableCol[] = [
  {
    type: 'multiple', // 多选框
    width: 50,
    align: 'center',
    colKey: 'checkbox',
  },
  {
    title: '序号',
    colKey: 'index',
    width: 80,
    align: 'center',
  },
  {
    title: '类别',
    colKey: 'name',
    width: 300,
    ellipsis: true,
    align: 'center',
  },
  {
    title: '创建时间',
    colKey: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    align: 'left',
    fixed: 'right',
    width: 160,
    colKey: 'op',
    title: '操作',
  },
];

// 表单验证规则
const rules: Record<string, FormRule[]> = {
  name: [
    { required: true, message: '请输入类别名称', type: 'error' },
    {
      validator: (val: string) => {
        if (!val || val.trim() === '') {
          return { result: false, message: '类别名称不能为空', type: 'error' };
        }
        return { result: true, message: '' };
      },
      message: '类别名称不能为空',
      type: 'error',
    },
    { max: 25, message: '类别名称不能超过25个字符', type: 'error' },
  ],
};

const rowKey = 'id';
const verticalAlign = 'top' as const;
const hover = true;
// 选中行
const selectedRowKeys = ref<number[]>([]);

// 分页配置 - 使用全局配置
const pagination = ref({ ...DEFAULT_PAGINATION });

// 数据相关
const data = ref<GuideCategoryResponse[]>([]);
const dataLoading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增类别');
const isEdit = ref(false);
const currentId = ref<number | null>(null);

// 表单相关
const formRef = ref();
const formData = ref<GuideCategoryRequest>({
  name: '',
});
const submitLoading = ref(false);

// Store
const store = useSettingStore();

// 表格行选择变化时的回调函数
const onSelectChange = (keys: (string | number)[], options: any) => {
  selectedRowKeys.value = keys as number[];
};

// 表头固定配置
// 当使用标签页路由时,偏移量为48px,否则为0
// 固定容器为布局组件
const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any,
);

onActivated(() => {
  fetchData();
});

/**
 * 获取指南类别列表数据
 */
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const res = await getGuideCategoryList({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
    });
    const records = res.data.data?.records ?? [];
    const total = res.data.data?.total ?? 0;
    data.value = records;
    pagination.value.total = total;
  } catch (e) {
    MessagePlugin.error('服务器繁忙，请稍后再试');
  } finally {
    dataLoading.value = false;
  }
};

/**
 * 批量删除类别
 */
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) return;
  const dialogInstance = DialogPlugin.confirm({
    header: '提示',
    body: '确定要批量删除选中的类别吗？',
    onConfirm: async () => {
      try {
        await deleteGuideCategory(selectedRowKeys.value);
        MessagePlugin.success('批量删除成功！');
        selectedRowKeys.value = [];
        fetchData();
      } catch (error) {
        MessagePlugin.error('删除的' + error.message + '，删除失败');
      } finally {
        dialogInstance.destroy();
      }
    },
  });
};

/**
 * 删除类别
 * @param slot 插槽参数
 */
const handleClickDelete = (slot: { row: { id: number } }) => {
  const dialogInstance = DialogPlugin.confirm({
    header: '提示',
    body: '确定要删除该类别吗？',
    onConfirm: async () => {
      try {
        await deleteGuideCategory([slot.row.id]);
        MessagePlugin.success('删除成功！');
        // 中文注释：删除成功后，把该 id 从选中数组中移除，避免批量删除时出错
        selectedRowKeys.value = selectedRowKeys.value.filter((id) => id !== slot.row.id);
        fetchData();
      } catch (error) {
        MessagePlugin.error('删除的' + error.message + '，删除失败');
      } finally {
        dialogInstance.destroy();
      }
    },
  });
};

/**
 * 分页变化处理
 */
const rehandlePageChange = (pageInfo: PageInfo) => {
  pagination.value.current = pageInfo.current;
  pagination.value.pageSize = pageInfo.pageSize;
  fetchData();
};

/**
 * 表格变化处理
 */
const rehandleChange = (changeParams: unknown, triggerAndData: unknown) => {
  console.log('表格变化:', changeParams, triggerAndData);
};

/**
 * 新增类别
 */
const handleAddCategory = () => {
  isEdit.value = false;
  dialogTitle.value = '新增类别';
  formData.value = { name: '' };
  dialogVisible.value = true;
};

/**
 * 编辑类别
 * @param row 行数据
 */
const handleEdit = (row: GuideCategoryResponse) => {
  isEdit.value = true;
  currentId.value = row.id;
  dialogTitle.value = '编辑类别';
  formData.value = {
    id: row.id,
    name: row.name,
  };
  dialogVisible.value = true;
};

/**
 * 表单提交
 */
const onSubmit = async () => {
  // 中文注释：去除首尾空格
  const name = formData.value.name.trim();

  // 中文注释：判断是否为空、''、""、''，都不允许添加
  if (!name || name === '""' || name === "''") {
    MessagePlugin.error('请输入有效的类别名称，不能为引号或空字符串');
    return;
  }

  formData.value.name = name; // 中文注释：保存去除空格后的内容

  const valid = await formRef.value?.validate();
  if (!valid) return;

  submitLoading.value = true;
  try {
    if (isEdit.value) {
      await updateGuideCategory(formData.value);
      MessagePlugin.success('更新成功！');
    } else {
      await addGuideCategory(formData.value);
      MessagePlugin.success('新增成功！');
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    MessagePlugin.error(isEdit.value ? '更新的' + error.message : '新增的' + error.message);
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
.guide-category-table {
  background-color: var(--td-bg-color-container);
  border-radius: var(--td-radius-large);
  box-shadow: var(--td-shadow-1);
  animation: fadeInUp 0.3s ease-out;

  // 顶栏样式
  .top-bar {
    padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-xl);
    background: linear-gradient(135deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
    border-bottom: 1px solid var(--td-border-level-1-color);
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 2px;
      background: linear-gradient(90deg, var(--td-brand-color) 0%, var(--td-brand-color-1) 100%);
    }

    .top-bar-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        h2 {
          font-size: 24px;
          font-weight: 600;
          color: var(--td-text-color-primary);
          margin-bottom: 4px;
        }
        p {
          font-size: 14px;
          color: var(--td-text-color-secondary);
        }
      }

      .top-bar-actions {
        display: flex;
        align-items: center;

        .t-tag {
          font-weight: 500;
          padding: 8px 16px;
          border-radius: var(--td-radius-medium);
          background: linear-gradient(135deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
          border: 1px solid var(--td-brand-color-1);
          color: var(--td-brand-color);
        }
      }
    }
  }

  // 操作区域样式
  .action-section {
    padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-xl);
    display: flex;
    align-items: center;
    background: var(--td-bg-color-container);
    border-bottom: 1px solid var(--td-border-level-1-color);
    gap: 16px;
    position: relative;

    .action-btn-group {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-left: 28px;

      .t-button {
        min-width: 120px;
        height: 40px;
        font-size: 16px;
        border-radius: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 500;
        box-sizing: border-box;
        padding: 0 20px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        .t-icon {
          font-size: 20px;
          margin-right: 6px;
        }
      }

      .t-button--theme-primary {
        background: var(--td-brand-color);
        color: #fff;
        border: none;

        &:hover {
          background: var(--td-brand-color-hover, var(--td-brand-color-1));
          transform: translateY(-2px);
          box-shadow: 0 4px 12px var(--td-brand-color-2);
        }
      }

      .t-button--theme-danger {
        background: var(--td-danger-bg, #f8d7da);
        color: var(--td-danger-color, #d9534f);
        border: none;

        &:hover {
          background: var(--td-danger-bg-hover, #f5c6cb);
          color: var(--td-danger-color-hover, #b52a2a);
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(217, 83, 79, 0.3);
        }

        &:disabled,
        &[disabled] {
          background: var(--td-bg-color-disabled, #f3f3f3);
          color: var(--td-text-color-disabled, #bdbdbd);
          border: none;
          cursor: not-allowed;
          transform: none;
          box-shadow: none;
        }
      }
    }
  }

  // 表格容器样式
  .table-container {
    padding: 0 0 var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
    background-color: var(--td-bg-color-container);

    :deep(.t-table) {
      border-radius: var(--td-radius-medium);
      /* 中文注释：移除overflow hidden，避免影响表头定位 */
      /* overflow: hidden; */
      box-shadow: var(--td-shadow-1);
      border: 1px solid var(--td-border-level-1-color);

      .t-table__header {
        background: linear-gradient(
          135deg,
          var(--td-bg-color-secondarycontainer) 0%,
          var(--td-bg-color-container) 100%
        );
        border-bottom: 2px solid var(--td-border-level-1-color);

        th {
          font-weight: 600;
          color: var(--td-text-color-primary);
          padding: 14px 12px;
          /* 中文注释：移除position relative，避免影响表头定位 */
          /* position: relative; */
          text-align: center;
          vertical-align: middle;
        }
      }

      .t-table__body {
        tr {
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          /* 中文注释：移除position relative，避免影响表头定位 */
          /* position: relative; */

          &:hover {
            background: linear-gradient(135deg, var(--td-bg-color-container-hover) 0%, var(--td-brand-color-1) 100%);
            transform: translateY(-2px);
            box-shadow: var(--td-shadow-2);
            z-index: 1;
          }

          td {
            padding: 14px 12px;
            border-bottom: 1px solid var(--td-border-level-1-color);
            text-align: center;
            vertical-align: middle;
            height: 48px;
          }

          &:last-child td {
            border-bottom: none;
          }
        }
      }
    }
  }

  // 序号列样式
  .index-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    color: var(--td-text-color-secondary);
    height: 100%;
    min-height: 36px;
  }

  // 类别名称列样式
  .name-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 36px;

    .name-content {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0;

      .name-icon {
        color: var(--td-brand-color);
        font-size: 16px;
        flex-shrink: 0;
      }

      .name-text {
        font-weight: 500;
        color: var(--td-text-color-primary);
        line-height: 1.4;
        max-width: 200px;
      }
    }
  }

  // 时间列样式
  .time-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    height: 100%;
    min-height: 36px;

    .time-icon {
      color: var(--td-text-color-placeholder);
      font-size: 14px;
    }

    .time-text {
      color: var(--td-text-color-secondary);
      font-size: 13px;
    }
  }

  // 操作列样式
  .operation-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 36px;

    .t-button {
      min-width: 60px;
      height: 32px;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 2px;
      border-radius: var(--td-radius-small);
      transition: all 0.2s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: var(--td-shadow-1);
      }
    }
  }
}

// 弹窗样式
:deep(.t-dialog) {
  .t-dialog__header {
    border-bottom: 1px solid var(--td-border-level-1-color);
    padding: 20px 24px;
    background: linear-gradient(135deg, var(--td-bg-color-secondarycontainer) 0%, var(--td-bg-color-container) 100%);
  }

  .t-dialog__body {
    padding: 24px;
  }

  .t-input {
    border-radius: var(--td-radius-medium);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border: 2px solid var(--td-border-level-1-color);

    &:hover {
      border-color: var(--td-brand-color-1);
      box-shadow: 0 0 0 3px var(--td-brand-color-2);
    }

    &:focus-within {
      border-color: var(--td-brand-color);
      box-shadow: 0 0 0 4px var(--td-brand-color-2);
      transform: translateY(-1px);
    }
  }
}

// 分页样式优化
:deep(.t-pagination) {
  margin-top: var(--td-comp-margin-xl);
  padding: var(--td-comp-paddingTB-lg) 0;
  border-top: 1px solid var(--td-border-level-1-color);
  background: linear-gradient(135deg, var(--td-bg-color-secondarycontainer) 0%, var(--td-bg-color-container) 100%);
  border-radius: 0 0 var(--td-radius-medium) var(--td-radius-medium);

  .t-pagination__total {
    color: var(--td-text-color-secondary);
    font-weight: 600;
  }

  .t-pagination__jumper {
    .t-input {
      border-radius: var(--td-radius-small);
      transition: all 0.2s ease;

      &:hover {
        border-color: var(--td-brand-color-1);
      }

      &:focus-within {
        border-color: var(--td-brand-color);
        box-shadow: 0 0 0 2px var(--td-brand-color-2);
      }
    }
  }

  .t-pagination__btn {
    transition: all 0.2s ease;
    border-radius: var(--td-radius-small);

    &:hover {
      transform: translateY(-1px);
      box-shadow: var(--td-shadow-1);
    }

    &.t-is-current {
      background: linear-gradient(135deg, var(--td-brand-color) 0%, var(--td-brand-color-1) 100%);
      color: white;
      box-shadow: 0 2px 8px var(--td-brand-color-2);
    }
  }
}

// 文本省略样式
.ellipsis {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .guide-category-table {
    .top-bar {
      padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-lg);

      .top-bar-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .page-title {
          margin-bottom: 0;
        }

        .top-bar-actions {
          margin-left: 0 !important;
        }
      }
    }

    .action-section {
      padding: var(--td-comp-paddingTB-lg) var(--td-comp-paddingLR-lg);
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .action-btn-group {
        justify-content: center;
      }
    }

    .table-container {
      padding: 0 var(--td-comp-paddingLR-lg) var(--td-comp-paddingTB-lg);
    }
  }
}

// 深色模式适配
:root[theme-mode='dark'] {
  .guide-category-table {
    box-shadow: var(--td-shadow-2);

    .top-bar {
      background: linear-gradient(135deg, var(--td-brand-color-2) 0%, var(--td-brand-color-3) 100%);

      &::before {
        background: linear-gradient(90deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
      }

      .top-bar-actions .t-tag {
        background: linear-gradient(135deg, var(--td-brand-color-2) 0%, var(--td-brand-color-3) 100%);
        border: 1px solid var(--td-brand-color-2);
        color: var(--td-brand-color-1);
      }
    }

    .action-section {
      .t-button--theme-primary {
        background: var(--td-brand-color-1);

        &:hover {
          background: var(--td-brand-color-2);
          box-shadow: 0 4px 12px var(--td-brand-color-3);
        }
      }

      .t-button--theme-danger {
        background: var(--td-danger-bg-dark, #3a2323);
        color: var(--td-danger-color-dark, #ffb3b3);

        &:hover {
          background: var(--td-danger-bg-hover-dark, #4a2a2a);
          color: var(--td-danger-color-hover-dark, #ffcccc);
          box-shadow: 0 4px 12px rgba(255, 179, 179, 0.3);
        }
      }
    }

    .table-container {
      :deep(.t-table) {
        box-shadow: var(--td-shadow-2);

        .t-table__header {
          background: linear-gradient(135deg, var(--td-brand-color-3) 0%, var(--td-brand-color-4) 100%);
        }

        .t-table__body tr:hover {
          background: linear-gradient(135deg, var(--td-bg-color-container-hover) 0%, var(--td-brand-color-2) 100%);
          box-shadow: var(--td-shadow-3);
        }
      }
    }
  }

  :deep(.t-dialog) {
    .t-dialog__header {
      background: linear-gradient(135deg, var(--td-brand-color-3) 0%, var(--td-brand-color-4) 100%);
    }
  }

  :deep(.t-pagination) {
    background: linear-gradient(135deg, var(--td-brand-color-3) 0%, var(--td-brand-color-4) 100%);

    .t-pagination__btn.t-is-current {
      background: linear-gradient(135deg, var(--td-brand-color-1) 0%, var(--td-brand-color-2) 100%);
      box-shadow: 0 2px 8px var(--td-brand-color-3);
    }
  }
}
</style>
